package com.xiaoxiaoniu.airoleplay.controller;

import com.xiaoxiaoniu.airoleplay.model.ChatRequest;
import com.xiaoxiaoniu.airoleplay.model.ChatResponse;
import com.xiaoxiaoniu.airoleplay.model.Conversation;
import com.xiaoxiaoniu.airoleplay.model.Message;
import com.xiaoxiaoniu.airoleplay.services.AIService;
import com.xiaoxiaoniu.airoleplay.services.ConversationService;
import com.xiaoxiaoniu.airoleplay.services.RoleSkillService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = {"http://localhost:5173", "http://127.0.0.1:5173"})
public class ChatController {

    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);

    @Autowired
    private ConversationService conversationService;

    @Autowired
    private AIService aiService;

    @Autowired
    private RoleSkillService roleSkillService;

    /**
     * 处理聊天消息 - 主要API端点
     */
    @PostMapping("/chat")
    public ResponseEntity<ChatResponse> chat(@Valid @RequestBody ChatRequest request) {
        try {
            // 验证请求参数
            if (request == null) {
                return ResponseEntity.badRequest()
                        .body(new ChatResponse(false, "请求体不能为空"));
            }

            if (request.getRole() == null || request.getRole().trim().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(new ChatResponse(false, "角色名称不能为空"));
            }

            if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(new ChatResponse(false, "消息内容不能为空"));
            }

            String role = request.getRole().trim();
            String userMessage = request.getMessage().trim();

            logger.info("收到聊天请求: role={}, message={}, conversationId={}",
                    role, userMessage, request.getConversationId());

            // 处理会话ID
            String conversationId = request.getConversationId();
            if (conversationId == null || conversationId.trim().isEmpty()) {
                conversationId = conversationService.createNewConversation(role);
                logger.info("创建新会话: {}", conversationId);
            } else {
                // 验证会话是否存在且属于当前角色
                Optional<Conversation> existingConv = conversationService.getConversation(conversationId);
                if (existingConv.isEmpty()) {
                    conversationId = conversationService.createNewConversation(role);
                    logger.info("会话不存在，创建新会话: {}", conversationId);
                } else if (!existingConv.get().getRoleName().equals(role)) {
                    // 如果角色不匹配，创建新会话
                    conversationId = conversationService.createNewConversation(role);
                    logger.info("角色不匹配，创建新会话: {}", conversationId);
                }
            }

            String finalReply;
            boolean isSkillTriggered = false;

            // 1. 首先检查并应用角色特殊技能
            String skillResponse = roleSkillService.checkAndApplySkill(role, userMessage);
            if (skillResponse != null) {
                finalReply = skillResponse;
                isSkillTriggered = true;
                logger.debug("触发角色特殊技能: {}", skillResponse);
            } else {
                // 2. 如果没有触发技能，调用AI服务
                try {
                    CompletableFuture<String> aiResponseFuture = aiService.getAIResponse(role, userMessage);
                    finalReply = aiResponseFuture.get(30, TimeUnit.SECONDS); // 30秒超时
                    logger.info("AI回复成功，长度: {}", finalReply.length());
                } catch (TimeoutException e) {
                    logger.warn("AI服务响应超时，使用智能备用回复");
                    finalReply = roleSkillService.getIntelligentFallback(role, userMessage);
                } catch (Exception e) {
                    logger.error("AI服务调用失败，使用智能备用回复", e);
                    finalReply = roleSkillService.getIntelligentFallback(role, userMessage);
                }
            }

            // 3. 保存消息到数据库
            conversationService.saveMessage(conversationId, role, userMessage, finalReply);

            // 4. 构建响应
            ChatResponse response = new ChatResponse(finalReply, conversationId);
            response.setSuccess(true);

            if (isSkillTriggered) {
                response.setReply("[技能触发] " + finalReply);
                logger.info("返回技能触发响应: conversationId={}, 技能回复长度={}",
                        conversationId, finalReply.length());
            } else {
                logger.info("返回AI响应: conversationId={}, 回复长度={}",
                        conversationId, finalReply.length());
            }

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("聊天处理失败", e);
            ChatResponse errorResponse = new ChatResponse(false,
                    "服务暂时不可用，请稍后重试: " + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }

    /**
     * 获取所有会话列表
     */
    @GetMapping("/conversations")
    public ResponseEntity<List<Conversation>> getAllConversations() {
        try {
            List<Conversation> conversations = conversationService.getAllConversations();
            logger.info("获取会话列表，数量: {}", conversations.size());
            return ResponseEntity.ok(conversations);
        } catch (Exception e) {
            logger.error("获取会话列表失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取特定会话的所有消息
     */
    @GetMapping("/conversations/{conversationId}/messages")
    public ResponseEntity<List<Message>> getConversationMessages(@PathVariable String conversationId) {
        try {
            // 验证会话是否存在
            Optional<Conversation> conversation = conversationService.getConversation(conversationId);
            if (conversation.isEmpty()) {
                return ResponseEntity.notFound().build();
            }

            List<Message> messages = conversationService.getConversationMessages(conversationId);
            logger.info("获取会话消息: conversationId={}, 消息数量={}", conversationId, messages.size());
            return ResponseEntity.ok(messages);
        } catch (Exception e) {
            logger.error("获取会话消息失败: {}", conversationId, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取会话的最新消息（限制数量）
     */
    @GetMapping("/conversations/{conversationId}/messages/latest")
    public ResponseEntity<List<Message>> getLatestMessages(
            @PathVariable String conversationId,
            @RequestParam(defaultValue = "10") int limit) {
        try {
            // 验证会话是否存在
            Optional<Conversation> conversation = conversationService.getConversation(conversationId);
            if (conversation.isEmpty()) {
                return ResponseEntity.notFound().build();
            }

            List<Message> messages = conversationService.getLatestMessages(conversationId, limit);
            logger.info("获取最新消息: conversationId={}, limit={}, 实际数量={}",
                    conversationId, limit, messages.size());
            return ResponseEntity.ok(messages);
        } catch (Exception e) {
            logger.error("获取最新消息失败: {}", conversationId, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取特定角色的所有会话
     */
    @GetMapping("/conversations/role/{roleName}")
    public ResponseEntity<List<Conversation>> getConversationsByRole(@PathVariable String roleName) {
        try {
            List<Conversation> conversations = conversationService.getConversationsByRole(roleName);
            logger.info("获取角色会话: roleName={}, 数量={}", roleName, conversations.size());
            return ResponseEntity.ok(conversations);
        } catch (Exception e) {
            logger.error("获取角色会话失败: {}", roleName, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 健康检查端点
     */
    @GetMapping("/health")
    public ResponseEntity<String> healthCheck() {
        String healthStatus = "AI角色扮演后端服务运行正常 - " + System.currentTimeMillis();
        logger.debug("健康检查: {}", healthStatus);
        return ResponseEntity.ok(healthStatus);
    }

    /**
     * 获取角色技能信息（调试用）
     */
    @GetMapping("/debug/skills/{roleName}")
    public ResponseEntity<Object> getRoleSkillsInfo(@PathVariable String roleName) {
        try {
            Object skillsInfo = roleSkillService.getRoleSkillsInfo(roleName);
            logger.info("获取角色技能信息: roleName={}", roleName);
            return ResponseEntity.ok(skillsInfo);
        } catch (Exception e) {
            logger.error("获取角色技能信息失败: {}", roleName, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 测试AI服务连通性
     */
    @GetMapping("/debug/ai-connection")
    public ResponseEntity<Object> testAIConnection() {
        try {
            CompletableFuture<Boolean> connectionTest = aiService.testAPIConnection();
            Boolean isConnected = connectionTest.get(10, TimeUnit.SECONDS);

            var response = new java.util.HashMap<String, Object>();
            response.put("success", true);
            response.put("ai_service_connected", isConnected);
            response.put("timestamp", System.currentTimeMillis());
            response.put("message", isConnected ? "AI服务连接正常" : "AI服务连接失败");

            logger.info("AI服务连通性测试: {}", isConnected ? "成功" : "失败");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("AI服务连通性测试失败", e);

            var errorResponse = new java.util.HashMap<String, Object>();
            errorResponse.put("success", false);
            errorResponse.put("ai_service_connected", false);
            errorResponse.put("timestamp", System.currentTimeMillis());
            errorResponse.put("error", e.getMessage());

            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }

    /**
     * 结束会话
     */
    @PostMapping("/conversations/{conversationId}/end")
    public ResponseEntity<Object> endConversation(@PathVariable String conversationId) {
        try {
            // 验证会话是否存在
            Optional<Conversation> conversation = conversationService.getConversation(conversationId);
            if (conversation.isEmpty()) {
                return ResponseEntity.notFound().build();
            }

            // 这里可以添加会话结束的逻辑，比如清理资源、生成总结等
            logger.info("结束会话: conversationId={}, roleName={}",
                    conversationId, conversation.get().getRoleName());

            var response = new java.util.HashMap<String, Object>();
            response.put("success", true);
            response.put("conversationId", conversationId);
            response.put("message", "会话已结束");
            response.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("结束会话失败: {}", conversationId, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取系统状态信息
     */
    @GetMapping("/status")
    public ResponseEntity<Object> getSystemStatus() {
        try {
            var status = new java.util.HashMap<String, Object>();

            // 基本系统信息
            status.put("service", "AI角色扮演后端");
            status.put("version", "1.0.0");
            status.put("timestamp", System.currentTimeMillis());
            status.put("status", "正常运行");

            // 数据库状态
            try {
                List<Conversation> conversations = conversationService.getAllConversations();
                status.put("database", "正常");
                status.put("conversation_count", conversations.size());

                long totalMessages = 0;
                for (Conversation conv : conversations) {
                    totalMessages += conversationService.getMessageCount(conv.getConversationId());
                }
                status.put("total_messages", totalMessages);
            } catch (Exception e) {
                status.put("database", "异常: " + e.getMessage());
            }

            // AI服务状态
            try {
                CompletableFuture<Boolean> aiTest = aiService.testAPIConnection();
                boolean aiConnected = aiTest.get(5, TimeUnit.SECONDS);
                status.put("ai_service", aiConnected ? "正常" : "异常");
            } catch (Exception e) {
                status.put("ai_service", "异常: " + e.getMessage());
            }

            logger.info("系统状态检查");
            return ResponseEntity.ok(status);
        } catch (Exception e) {
            logger.error("获取系统状态失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 批量删除会话（管理功能）
     */
    @DeleteMapping("/conversations")
    public ResponseEntity<Object> deleteConversations(@RequestParam List<String> conversationIds) {
        try {
            // 在实际项目中，这里应该实现具体的删除逻辑
            // 目前只是记录日志并返回成功

            logger.info("批量删除会话: {}", conversationIds);

            var response = new java.util.HashMap<String, Object>();
            response.put("success", true);
            response.put("deleted_count", conversationIds.size());
            response.put("message", "删除功能待实现（演示版本）");
            response.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("批量删除会话失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
}